# -*- coding: utf-8 -*-
"""
教练预约管理视图

包含教练预约管理的所有页面和API：
- 待确认预约列表
- 已确认预约管理
- 个人课程表
- 预约详情
- 确认/拒绝预约
- 取消预约
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from datetime import datetime, date, timedelta
from sqlalchemy import and_, or_

from app.decorators import coach_required
from app.controllers.reservation_controller import ReservationController
from app.models.reservation import Reservation
from app import db

# 创建教练预约蓝图
coach_reservations_bp = Blueprint('coach_reservations', __name__)


@coach_reservations_bp.route('/pending')
@login_required
@coach_required
def pending():
    """
    待确认预约列表页面

    显示需要教练确认的预约申请
    """
    page = request.args.get('page', 1, type=int)
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')

    # 构建查询
    query = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status == 'pending'
    )

    # 日期筛选
    if start_date:
        try:
            start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
            query = query.filter(Reservation.reservation_date >= start_date_obj)
        except ValueError:
            start_date = ''

    if end_date:
        try:
            end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
            query = query.filter(Reservation.reservation_date <= end_date_obj)
        except ValueError:
            end_date = ''

    # 按日期升序排列
    query = query.order_by(Reservation.reservation_date.asc(), Reservation.start_time.asc())

    # 分页
    pagination = query.paginate(page=page, per_page=15, error_out=False)

    # 获取统计数据
    total_pending = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status == 'pending'
    ).count()

    today_pending = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status == 'pending',
        Reservation.reservation_date == date.today()
    ).count()

    # 计算过期的待确认预约（超过24小时未处理）
    expired_pending = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status == 'pending',
        Reservation.created_at < datetime.now() - timedelta(hours=24)
    ).count()

    statistics = {
        'total_pending': total_pending,
        'today_pending': today_pending,
        'expired_pending': expired_pending
    }

    # 传递当前日期和时间给模板
    current_date = date.today()
    current_datetime = datetime.now()

    return render_template('coach_reservations/pending.html',
                         reservations=pagination.items,
                         pagination=pagination,
                         statistics=statistics,
                         filter_params={
                             'start_date': start_date,
                             'end_date': end_date
                         },
                         current_date=current_date,
                         current_datetime=current_datetime)


@coach_reservations_bp.route('/confirmed')
@login_required
@coach_required
def confirmed():
    """
    已确认预约列表页面

    显示教练已确认的预约
    """
    page = request.args.get('page', 1, type=int)
    status_filter = request.args.get('status', 'confirmed')
    start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '')

    # 构建查询
    if status_filter == 'all':
        query = Reservation.query.filter(
            Reservation.coach_id == current_user.id,
            Reservation.status.in_(['confirmed', 'completed', 'cancelled', 'no_show'])
        )
    else:
        query = Reservation.query.filter(
            Reservation.coach_id == current_user.id,
            Reservation.status == status_filter
        )

    # 日期筛选
    if start_date:
        try:
            start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
            query = query.filter(Reservation.reservation_date >= start_date_obj)
        except ValueError:
            start_date = ''

    if end_date:
        try:
            end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
            query = query.filter(Reservation.reservation_date <= end_date_obj)
        except ValueError:
            end_date = ''

    # 按日期降序排列
    query = query.order_by(Reservation.reservation_date.desc(), Reservation.start_time.desc())

    # 分页
    pagination = query.paginate(page=page, per_page=15, error_out=False)

    # 获取统计数据
    confirmed_count = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status == 'confirmed'
    ).count()

    completed_count = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status == 'completed'
    ).count()

    cancelled_count = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status == 'cancelled'
    ).count()

    statistics = {
        'confirmed_count': confirmed_count,
        'completed_count': completed_count,
        'cancelled_count': cancelled_count
    }

    # 传递当前日期和时间给模板
    current_date = date.today()
    current_datetime = datetime.now()

    return render_template('coach_reservations/confirmed.html',
                         reservations=pagination.items,
                         pagination=pagination,
                         statistics=statistics,
                         current_status=status_filter,
                         filter_params={
                             'status': status_filter,
                             'start_date': start_date,
                             'end_date': end_date
                         },
                         current_date=current_date,
                         current_datetime=current_datetime)


@coach_reservations_bp.route('/schedule')
@login_required
@coach_required
def schedule():
    """
    个人课程表页面

    支持周视图和日视图
    """
    view_type = request.args.get('view', 'week')  # week 或 day
    date_str = request.args.get('date', date.today().isoformat())

    try:
        target_date = datetime.strptime(date_str, '%Y-%m-%d').date()
    except ValueError:
        target_date = date.today()

    if view_type == 'week':
        # 计算周的开始和结束日期
        start_date = target_date - timedelta(days=target_date.weekday())
        end_date = start_date + timedelta(days=6)
    else:  # day view
        start_date = target_date
        end_date = target_date

    # 获取指定时间范围内的预约
    reservations = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.status.in_(['pending', 'confirmed', 'completed']),
        Reservation.reservation_date >= start_date,
        Reservation.reservation_date <= end_date
    ).order_by(Reservation.reservation_date, Reservation.start_time).all()

    # 为预约添加状态显示属性
    for reservation in reservations:
        if reservation.status == 'pending':
            reservation.status_color = 'warning'
            reservation.status_text = '待确认'
        elif reservation.status == 'confirmed':
            reservation.status_color = 'success'
            reservation.status_text = '已确认'
        elif reservation.status == 'completed':
            reservation.status_color = 'primary'
            reservation.status_text = '已完成'
        else:
            reservation.status_color = 'secondary'
            reservation.status_text = reservation.status

    # 按日期分组预约
    schedule_data = {}
    current_date_iter = start_date
    while current_date_iter <= end_date:
        schedule_data[current_date_iter.isoformat()] = []
        current_date_iter += timedelta(days=1)

    for reservation in reservations:
        date_key = reservation.reservation_date.isoformat()
        if date_key in schedule_data:
            schedule_data[date_key].append(reservation)

    # 准备周视图数据
    week_days = []
    if view_type == 'week':
        weekday_names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        current_date_iter = start_date
        for i in range(7):
            week_days.append({
                'date': current_date_iter,
                'weekday': weekday_names[i],
                'is_today': current_date_iter == date.today(),
                'reservations': schedule_data.get(current_date_iter.isoformat(), [])
            })
            current_date_iter += timedelta(days=1)

    # 准备日视图数据
    daily_reservations = []
    if view_type == 'day':
        daily_reservations = schedule_data.get(target_date.isoformat(), [])

    # 今日课程数量
    today_reservations = Reservation.query.filter(
        Reservation.coach_id == current_user.id,
        Reservation.reservation_date == date.today(),
        Reservation.status.in_(['confirmed', 'completed'])
    ).count()

    # 获取当周/当日统计
    total_reservations = len(reservations)
    total_hours = sum(r.duration_minutes for r in reservations) / 60
    total_income = sum(float(r.price) for r in reservations if r.price)

    statistics = {
        'total_reservations': total_reservations,
        'total_hours': round(total_hours, 1),
        'total_income': round(total_income, 2)
    }

    # 如果是AJAX请求，返回JSON格式数据
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
        try:
            # 准备时间段文本
            if view_type == 'week':
                period_text = f"{start_date.strftime('%Y年%m月%d日')} - {end_date.strftime('%m月%d日')}"
            else:
                weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
                period_text = f"{target_date.strftime('%Y年%m月%d日')} {weekdays[target_date.weekday()]}"

            # 准备JSON响应的预约数据
            json_schedule_data = {}
            for date_key, date_reservations in schedule_data.items():
                json_reservations = []
                for reservation in date_reservations:
                    json_reservations.append({
                        'id': reservation.id,
                        'student_name': reservation.student.name,
                        'start_time': reservation.start_time.strftime('%H:%M'),
                        'end_time': reservation.end_time.strftime('%H:%M'),
                        'time_range': f"{reservation.start_time.strftime('%H:%M')}-{reservation.end_time.strftime('%H:%M')}",
                        'table_name': reservation.table.name,
                        'status': reservation.status,
                        'status_color': reservation.status_color,
                        'status_text': reservation.status_text,
                        'start_hour': reservation.start_time.hour,
                        'notes': getattr(reservation, 'notes', '')
                    })
                json_schedule_data[date_key] = json_reservations

            return jsonify({
                'success': True,
                'data': {
                    'schedule': json_schedule_data,
                    'period_text': period_text,
                    'statistics': statistics
                }
            })
        except Exception as e:
            return jsonify({'success': False, 'message': f'加载课程表失败：{str(e)}'})

    # 普通页面请求，返回HTML页面
    return render_template('coach_reservations/schedule.html',
                         schedule_data=schedule_data,
                         view_type=view_type,
                         target_date=target_date,
                         current_date=target_date,
                         start_date=start_date,
                         end_date=end_date,
                         current_week_start=start_date,
                         current_week_end=end_date,
                         week_days=week_days,
                         daily_reservations=daily_reservations,
                         today_count=today_reservations,
                         statistics=statistics)


@coach_reservations_bp.route('/detail/<int:reservation_id>')
@login_required
@coach_required
def detail(reservation_id):
    """
    预约详情页面（教练视角）
    支持AJAX请求返回JSON格式，普通请求返回完整页面
    """
    result = ReservationController.get_reservation_detail(
        reservation_id=reservation_id,
        user_id=current_user.id
    )

    if not result['success']:
        # 如果是AJAX请求，返回JSON错误
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
            return jsonify({'success': False, 'message': result['message']})

        flash(result['message'], 'error')
        return redirect(url_for('coach_reservations.pending'))

    reservation_data = result['data']
    reservation = reservation_data['reservation']

    # 教练特定的操作权限
    coach_permissions = {
        'can_confirm': reservation.status == 'pending',
        'can_reject': reservation.status == 'pending',
        'can_cancel': reservation.status == 'confirmed' and reservation.can_be_cancelled(),
        'can_complete': reservation.status == 'confirmed' and reservation.get_datetime_end() <= datetime.now(),
        'can_mark_no_show': reservation.status == 'confirmed' and reservation.get_datetime_start() <= datetime.now()
    }

    reservation_data.update(coach_permissions)

    # 如果是AJAX请求，返回JSON格式（包含渲染的HTML片段）
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
        try:
            html_content = render_template('coach_reservations/detail_modal.html',
                                         reservation_data=reservation_data,
                                         reservation=reservation)
            # 准备可序列化的数据（移除Reservation对象）
            serializable_data = {
                'reservation_id': reservation.id,
                'status': reservation.status,
                'can_confirm': coach_permissions.get('can_confirm', False),
                'can_reject': coach_permissions.get('can_reject', False),
                'can_cancel': coach_permissions.get('can_cancel', False),
                'can_complete': coach_permissions.get('can_complete', False),
                'can_mark_no_show': coach_permissions.get('can_mark_no_show', False)
            }
            return jsonify({
                'success': True,
                'html': html_content,
                'data': serializable_data
            })
        except Exception as e:
            return jsonify({'success': False, 'message': f'渲染详情失败：{str(e)}'})

    # 普通页面请求，返回完整页面
    return render_template('coach_reservations/detail.html',
                         reservation_data=reservation_data,
                         reservation=reservation)


@coach_reservations_bp.route('/cancel/<int:reservation_id>', methods=['GET', 'POST'])
@login_required
@coach_required
def cancel(reservation_id):
    """
    教练取消预约页面
    """
    # 获取预约详情
    result = ReservationController.get_reservation_detail(
        reservation_id=reservation_id,
        user_id=current_user.id
    )

    if not result['success']:
        flash(result['message'], 'error')
        return redirect(url_for('coach_reservations.confirmed'))

    reservation = result['data']['reservation']

    # 检查是否可以取消
    if not (reservation.status == 'confirmed' and reservation.can_be_cancelled()):
        flash('该预约无法取消', 'error')
        return redirect(url_for('coach_reservations.detail', reservation_id=reservation_id))

    if request.method == 'POST':
        reason = request.form.get('reason', '').strip()
        additional_notes = request.form.get('additional_notes', '').strip()

        if not reason:
            flash('请填写取消原因', 'error')
        else:
            # 构建完整的取消原因
            cancel_reason = f"教练取消：{reason}"
            if additional_notes:
                cancel_reason += f"。{additional_notes}"

            # 执行取消
            cancel_result = ReservationController.cancel_reservation(
                reservation_id=reservation_id,
                user_id=current_user.id,
                reason=cancel_reason
            )

            if cancel_result['success']:
                flash('预约已成功取消', 'success')
                return redirect(url_for('coach_reservations.confirmed'))
            else:
                flash(cancel_result['message'], 'error')

    return render_template('coach_reservations/cancel.html',
                         reservation=reservation)


# API 接口

@coach_reservations_bp.route('/api/confirm/<int:reservation_id>', methods=['POST'])
@login_required
@coach_required
def api_confirm_reservation(reservation_id):
    """
    API：确认预约
    """
    try:
        reservation = Reservation.query.get(reservation_id)
        if not reservation:
            return jsonify({'success': False, 'message': '预约不存在'})

        # 权限验证
        if reservation.coach_id != current_user.id:
            return jsonify({'success': False, 'message': '无权限操作此预约'})

        # 状态验证
        if reservation.status != 'pending':
            return jsonify({'success': False, 'message': '只能确认待处理的预约'})

        # 确认预约
        success = reservation.confirm()
        if success:
            db.session.commit()
            return jsonify({
                'success': True,
                'message': '预约已确认',
                'data': {'status': reservation.status}
            })
        else:
            return jsonify({'success': False, 'message': '确认预约失败'})

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'})


@coach_reservations_bp.route('/api/reject/<int:reservation_id>', methods=['POST'])
@login_required
@coach_required
def api_reject_reservation(reservation_id):
    """
    API：拒绝预约
    """
    try:
        reason = request.json.get('reason', '').strip()
        if not reason:
            return jsonify({'success': False, 'message': '请填写拒绝原因'})

        reservation = Reservation.query.get(reservation_id)
        if not reservation:
            return jsonify({'success': False, 'message': '预约不存在'})

        # 权限验证
        if reservation.coach_id != current_user.id:
            return jsonify({'success': False, 'message': '无权限操作此预约'})

        # 状态验证
        if reservation.status != 'pending':
            return jsonify({'success': False, 'message': '只能拒绝待处理的预约'})

        # 拒绝预约 - 使用cancelled状态，通过cancel_reason区分是拒绝还是取消
        reservation.status = 'cancelled'
        reservation.cancel_reason = f"教练拒绝：{reason}"
        reservation.cancelled_at = datetime.now()
        reservation.cancelled_by = current_user.id
        reservation.updated_at = datetime.now()

        db.session.commit()

        return jsonify({
            'success': True,
            'message': '已拒绝预约',
            'data': {'status': reservation.status}
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'})


@coach_reservations_bp.route('/api/complete/<int:reservation_id>', methods=['POST'])
@login_required
@coach_required
def api_complete_reservation(reservation_id):
    """
    API：完成课程
    """
    try:
        reservation = Reservation.query.get(reservation_id)
        if not reservation:
            return jsonify({'success': False, 'message': '预约不存在'})

        # 权限验证
        if reservation.coach_id != current_user.id:
            return jsonify({'success': False, 'message': '无权限操作此预约'})

        # 完成课程
        success = reservation.complete()
        if success:
            db.session.commit()
            return jsonify({
                'success': True,
                'message': '课程已标记为完成',
                'data': {'status': reservation.status}
            })
        else:
            return jsonify({'success': False, 'message': '无法完成此课程'})

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'})


@coach_reservations_bp.route('/api/mark-no-show/<int:reservation_id>', methods=['POST'])
@login_required
@coach_required
def api_mark_no_show(reservation_id):
    """
    API：标记学员未出席
    """
    try:
        reservation = Reservation.query.get(reservation_id)
        if not reservation:
            return jsonify({'success': False, 'message': '预约不存在'})

        # 权限验证
        if reservation.coach_id != current_user.id:
            return jsonify({'success': False, 'message': '无权限操作此预约'})

        # 标记未出席
        success = reservation.mark_no_show()
        if success:
            db.session.commit()
            return jsonify({
                'success': True,
                'message': '已标记为未出席',
                'data': {'status': reservation.status}
            })
        else:
            return jsonify({'success': False, 'message': '无法标记此状态'})

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'})


@coach_reservations_bp.route('/api/batch-confirm', methods=['POST'])
@login_required
@coach_required
def api_batch_confirm():
    """
    API：批量确认预约
    """
    try:
        reservation_ids = request.json.get('reservation_ids', [])
        if not reservation_ids:
            return jsonify({'success': False, 'message': '请选择要确认的预约'})

        confirmed_count = 0
        failed_count = 0

        for reservation_id in reservation_ids:
            reservation = Reservation.query.get(reservation_id)
            if (reservation and
                reservation.coach_id == current_user.id and
                reservation.status == 'pending'):

                success = reservation.confirm()
                if success:
                    confirmed_count += 1
                else:
                    failed_count += 1
            else:
                failed_count += 1

        db.session.commit()

        return jsonify({
            'success': True,
            'message': f'成功确认 {confirmed_count} 个预约' + (f'，{failed_count} 个失败' if failed_count > 0 else ''),
            'data': {
                'confirmed_count': confirmed_count,
                'failed_count': failed_count
            }
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'批量操作失败：{str(e)}'})


@coach_reservations_bp.route('/api/today-schedule')
@login_required
@coach_required
def api_today_schedule():
    """
    API：获取今日课程安排
    """
    try:
        today = date.today()
        reservations = Reservation.query.filter(
            Reservation.coach_id == current_user.id,
            Reservation.reservation_date == today,
            Reservation.status.in_(['confirmed', 'completed'])
        ).order_by(Reservation.start_time).all()

        schedule_data = []
        for reservation in reservations:
            schedule_data.append({
                'id': reservation.id,
                'student_name': reservation.student.real_name,
                'start_time': reservation.start_time.strftime('%H:%M'),
                'end_time': reservation.end_time.strftime('%H:%M'),
                'table_name': reservation.table.name,
                'status': reservation.status,
                'is_upcoming': reservation.is_upcoming(),
                'can_complete': reservation.can_be_completed(),
                'can_mark_no_show': reservation.status == 'confirmed' and reservation.get_datetime_start() <= datetime.now()
            })

        return jsonify({
            'success': True,
            'data': {
                'reservations': schedule_data,
                'total_count': len(schedule_data)
            }
        })

    except Exception as e:
        return jsonify({'success': False, 'message': f'获取课程安排失败：{str(e)}'})


@coach_reservations_bp.route('/api/weekly-stats')
@login_required
@coach_required
def api_weekly_stats():
    """
    API：获取本周统计数据
    """
    try:
        today = date.today()
        week_start = today - timedelta(days=today.weekday())
        week_end = week_start + timedelta(days=6)

        # 获取本周预约
        reservations = Reservation.query.filter(
            Reservation.coach_id == current_user.id,
            Reservation.reservation_date >= week_start,
            Reservation.reservation_date <= week_end
        ).all()

        # 按状态统计
        stats = {
            'pending': 0,
            'confirmed': 0,
            'completed': 0,
            'cancelled': 0,
            'total_hours': 0,
            'total_income': 0
        }

        for reservation in reservations:
            if reservation.status in stats:
                stats[reservation.status] += 1

            if reservation.status in ['confirmed', 'completed']:
                stats['total_hours'] += reservation.duration_minutes / 60
                if reservation.price:
                    stats['total_income'] += float(reservation.price)

        stats['total_hours'] = round(stats['total_hours'], 1)
        stats['total_income'] = round(stats['total_income'], 2)

        return jsonify({
            'success': True,
            'data': stats
        })

    except Exception as e:
        return jsonify({'success': False, 'message': f'获取统计数据失败：{str(e)}'})


@coach_reservations_bp.route('/api/search-reservations')
@login_required
@coach_required
def api_search_reservations():
    """
    API：搜索预约
    """
    try:
        keyword = request.args.get('keyword', '').strip()
        status = request.args.get('status', '')
        date_from = request.args.get('date_from', '')
        date_to = request.args.get('date_to', '')

        query = Reservation.query.filter(Reservation.coach_id == current_user.id)

        # 关键词搜索（学员姓名或手机）
        if keyword:
            query = query.join(Reservation.student).filter(
                or_(
                    Reservation.student.has(User.real_name.contains(keyword)),
                    Reservation.student.has(User.phone.contains(keyword))
                )
            )

        # 状态筛选
        if status:
            query = query.filter(Reservation.status == status)

        # 日期筛选
        if date_from:
            query = query.filter(Reservation.reservation_date >= date_from)
        if date_to:
            query = query.filter(Reservation.reservation_date <= date_to)

        reservations = query.order_by(
            Reservation.reservation_date.desc(),
            Reservation.start_time.desc()
        ).limit(50).all()

        results = []
        for reservation in reservations:
            results.append({
                'id': reservation.id,
                'student_name': reservation.student.real_name,
                'student_phone': reservation.student.phone,
                'reservation_date': reservation.reservation_date.isoformat(),
                'start_time': reservation.start_time.strftime('%H:%M'),
                'end_time': reservation.end_time.strftime('%H:%M'),
                'status': reservation.status,
                'status_display': reservation.get_status_display(),
                'table_name': reservation.table.name
            })

        return jsonify({
            'success': True,
            'data': {'reservations': results}
        })

    except Exception as e:
        return jsonify({'success': False, 'message': f'搜索失败：{str(e)}'})


@coach_reservations_bp.route('/api/cancel/<int:reservation_id>', methods=['POST'])
@login_required
@coach_required
def api_cancel_reservation(reservation_id):
    """
    API：取消预约
    """
    try:
        reason = request.json.get('reason', '').strip() if request.is_json else request.form.get('reason', '').strip()
        if not reason:
            return jsonify({'success': False, 'message': '请填写取消原因'})

        reservation = Reservation.query.get(reservation_id)
        if not reservation:
            return jsonify({'success': False, 'message': '预约不存在'})

        # 权限验证
        if reservation.coach_id != current_user.id:
            return jsonify({'success': False, 'message': '无权限操作此预约'})

        # 状态验证
        if not (reservation.status == 'confirmed' and reservation.can_be_cancelled()):
            return jsonify({'success': False, 'message': '该预约无法取消'})

        # 使用 ReservationController 取消预约
        from app.controllers.reservation_controller import ReservationController
        cancel_result = ReservationController.cancel_reservation(
            reservation_id=reservation_id,
            user_id=current_user.id,
            reason=f"教练取消：{reason}"
        )

        if cancel_result['success']:
            return jsonify({
                'success': True,
                'message': '预约已成功取消',
                'data': {'status': 'cancelled'}
            })
        else:
            return jsonify({'success': False, 'message': cancel_result['message']})

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'操作失败：{str(e)}'})